package com.hxzy.common.exception;

import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Desc springmvc的全局异常处理类
 * @Author: admin
 * @Date: 2023/08/16/10:48
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = BindException.class)
    public R bindingException(BindException e){
        log.error(e);
        //得到所有的错误中的第一个
        String error=e.getAllErrors().get(0).getDefaultMessage();

        R<Object> build = R.build(AckCode.SYSTEM_PARAM_FAIL);
        build.setMsg(error);

        return build;
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public R serviceException(ServiceException e){
        return R.build(e.getAckCode());
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceStringException.class)
    public R serviceStringException(ServiceStringException e){
        return e.getR();
    }

}
